package com.joinway.framework.data.jdbc.service;

import com.joinway.framework.data.jdbc.bean.SelectClause;
import com.joinway.framework.data.jdbc.bean.WhereClause;
import com.joinway.framework.data.jdbc.repository.TableRepository;
import com.joinway.framework.extension.utils.DateTimeUtils;

abstract class AbstractSqlService {

	protected TableRepository repository;
	
	public AbstractSqlService(TableRepository repository){
		this.repository = repository;
	}

	protected int getDataCount(String table, WhereClause wc){
		List<?> list = repository.find("select count(*) total from $table " + wc.getWhere(), wc.getParams());
		return list ? list[0].total : 0
	}
	
	protected int getDataCount(SelectClause sc){
		String sql = sc.toString();
		
		WhereClause wc = sc.getWhereClause();
		
		List<?> list;
		if(wc != null){
			list = repository.find("select count(*) total from ($sql) t", wc.getParams());
		}else{
			list = repository.find("select count(*) total from ($sql) t");
		}
		
		return list ? list[0].total : 0
	}
	
	protected static def getFieldValue(def fieldValue){
		def value = fieldValue;
		
		if(fieldValue instanceof String){
			if(fieldValue =~ /\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}/){
				value = DateTimeUtils.convertToDate(fieldValue)
			}
		}
		
		return value;
	}

}
